<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\Agent;

use App\Constants\Constants;
use App\Dao\AgentDao;
use App\Dao\LocationDao;
use App\Kernel\Util\AgentJwtInstance;
use App\Service\Service;

use Hyperf\Di\Annotation\Inject;

/**
 * 用户登陆服务
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Service\Admin
 */
class StoreService extends Service
{
    /**
     * 后台用户
     *
     * @Inject
     * @var AgentDao
     */
    public $agent_dao;

    /**
     * @Inject
     * @var LocationDao
     */
    public $location_dao;

    /**
     * 用户登录处理
     *
     * @param string $phone 手机号码
     * @param string $login_pwd  登录密码
     * @return array
     */
    public function login(string $phone, string $login_pwd)
    {

        // 获取或创建用户
        if (!$user = $this->agent_dao->loginByPhone($phone)) {
            $this->error('USER.LOGIN_FAILED');
        }

        //验证密码
        if( !password_verify( $login_pwd, $user->login_pwd ) ) {
            $this->error('USER.REGISTER_FAIL');
        }

        // check user status
        if ($user->status == 2) {
            $this->error('此账号已停止服务');
        }

        // check user status
        if ($user->status !== 1) {
            $this->error('USER.STATUS_EXCEPTION');
        }

        return [
            'token' => (string)AgentJwtInstance::instance()->encode($user),
        ];
    }

    /**
     * 找回密码 - 验证手机
     * @param string $phone
     * @param string $code
     * @return mixed
     */
    public function retrievePhone(string $phone, string $code)
    {
        // 判断验证码是否输入正确
        $record = $this->redis->get(Constants::CODE_REDIS_PREFIX . $phone);
        $record = !$record ?: json_decode($record, true);
        if (!$record || !isset($record['code']) || (string)$record['code'] !== $code) {
            $this->error('COMMON.CODE_ERROR');
        }
        $this->redis->del(Constants::CODE_REDIS_PREFIX . $phone);

        $result = $this->agent_dao->getPhoneByUser( $phone, [
            'id'
        ]);

        return $result;
    }

    /**
     * 获取分公司直招区代理代理区域
     */
    public function getSubordinate()
    {
        $agent = AgentJwtInstance::instance()->build()->getAgent();

        if( $agent['identity'] == 1 || $agent['identity'] == 2 ) {
            $this->error("COMMON.HANDLE_FAILED");
        }

        $result = $this->agent_dao->mapMany([
            'identity' => 1,
            'inviter_id' => $agent['id'],
        ],false);

        $data = [];
        if( $result ) {
            foreach ( $result as $key => $value ) {
                $location = $this->location_dao->getLocationByPid([
                    'pid' => $value['location_id']
                ]);

                $data[$key]['id'] = $value['id'];
                $data[$key]['name'] = $value['name'];
                $data[$key]['location_name'] = $location['name'];
                $data[$key]['location_pid'] = $location['pid'];
            }
        }

        return $data;
    }

    /**
     * 获取分公司直招合伙人
     */
    public function getPartnerArea()
    {
        $agent = AgentJwtInstance::instance()->build()->getAgent();

        if( $agent['identity'] == 1 || $agent['identity'] == 2 ) {
            $this->error("COMMON.HANDLE_FAILED");
        }

        $partner = $this->agent_dao->mapMany([
            'inviter_id' => $agent['id'],
            'identity' => 4,
        ],false);

        $ids = [];
        foreach ( $partner as $item ) {
            $ids[] = $item['id'];
        }

        $partner = $this->agent_dao->mapMany([
            'inviter_id' => ['in',$ids],
            'identity' => 1,
        ],false);

        $data = [];
        if( $partner ) {
            foreach ( $partner as $key => $value ) {
                $location = $this->location_dao->getLocationByPid([
                    'pid' => $value['location_id']
                ]);

                $data[$key]['id'] = $value['id'];
                $data[$key]['name'] = $value['name'];
                $data[$key]['location_name'] = $location['name'];
                $data[$key]['location_pid'] = $location['pid'];
            }
        }

        return $data;
    }

    /**
     *  获取代理商\合伙人分润
     */
    public function getAgentShare()
    {
        $agent = AgentJwtInstance::instance()->build()->getAgent();

        if( $agent['identity'] == 1 || $agent['identity'] == 2 ) {
            $this->error("COMMON.HANDLE_FAILED");
        }

        $data['area_agent_money'] = $agent['area_agent_money'] ?? 0.0;
        $data['city_agent_money'] = $agent['city_agent_money'] ?? 0.0;
        $data['channel_agent_money'] = $agent['channel_agent_money'] ?? 0.0;

        return $data;
    }

    /**
     * 通过ID获取合伙人分润比例
     * @param int $partner_id
     * @return mixed
     */
    public function getAgentShareById(int $partner_id)
    {
        $agent = $this->agent_dao->first($partner_id);

        if( $agent['identity'] == 1 || $agent['identity'] == 2 ||  $agent['identity'] == 3) {
            $this->error("COMMON.HANDLE_FAILED");
        }

        $data['area_agent_money'] = $agent['area_agent_money'] ?? 0.0;
        $data['city_agent_money'] = $agent['city_agent_money'] ?? 0.0;
        $data['channel_agent_money'] = $agent['channel_agent_money'] ?? 0.0;

        return $data;
    }

    /**
     * 重置合伙人区代\市代密码
     * @param int $agent_id
     * @param int $partner_id
     * @return mixed
     */
    public function resetPasswordById( int $agent_id, int $partner_id)
    {
        $agent = $this->agent_dao->first($agent_id);

        if( $agent['identity'] != 1 && $agent['identity'] != 2) {
            $this->error("AGENT.NUMBER_STATUS_NOT");
        }

        if( $agent['inviter_id'] !=  $partner_id) {
            $this->error("AGENT.NOT_AGENT");
        }

        return $this->agent_dao->updateDataById($agent_id,[
            'login_pwd' => password_hash($agent['phone'],PASSWORD_DEFAULT)
        ]);
    }

    /**
     * 删除合伙人区代\市代
     * @param int $agent_id
     * @param int $partner_id
     * @return mixed
     */
    public function deleteAreaCityAgent( int $agent_id, int $partner_id )
    {
        $agent = $this->agent_dao->first($agent_id);

        if( $agent['identity'] != 1 && $agent['identity'] != 2) {
            $this->error("AGENT.NUMBER_STATUS_NOT");
        }

        if( $agent['inviter_id'] !=  $partner_id) {
            $this->error("AGENT.NOT_AGENT");
        }

        return $this->agent_dao->delete($agent_id);
    }

    /**
     * 调整合伙人区代\市代的状态
     * @param int $agent_id
     * @param int $partner_id
     * @return int
     */
    public function setAreaCityStatus(int $agent_id, int $partner_id)
    {
        $agent = $this->agent_dao->first($agent_id);

        if( $agent['identity'] != 1 && $agent['identity'] != 2) {
            $this->error("AGENT.NUMBER_STATUS_NOT");
        }

        if( $agent['inviter_id'] !=  $partner_id) {
            $this->error("AGENT.NOT_AGENT");
        }

        switch ($agent['status']) {
            case "1"://开启状态
                return $this->agent_dao->updateDataById($agent_id,[
                    'status' => 2
                ]);
                break;
            case "2"://禁用状态
                return $this->agent_dao->updateDataById($agent_id,[
                    'status' => 1
                ]);
                break;
            default:
                $this->error("USER.STATUS_EXCEPTION");
        }
    }
}